// -*- coding: utf-8 -*-
frappe.ui.form.on('Scrap Receipt', {
    refresh: function(frm) {
        // 根据状态显示不同按钮
        if (frm.doc.status === '草稿') {
            frm.add_custom_button(__('提交审批'), function() {
                submit_for_approval(frm);
            });
        }
        
        if (frm.doc.status === '待审核') {
            // 检查当前用户是否有审批权限
            if (frappe.user.has_role('Scrap Manager') || frappe.user.has_role('System Manager')) {
                frm.add_custom_button(__('审批通过'), function() {
                    approve_receipt(frm, true);
                });
                
                frm.add_custom_button(__('审批拒绝'), function() {
                    approve_receipt(frm, false);
                });
            }
        }
        
        // 添加查看余料详情按钮
        if (frm.doc.scrap_materials && frm.doc.scrap_materials.length > 0) {
            frm.add_custom_button(__('查看余料详情'), function() {
                show_scrap_materials_details(frm);
            });
        }
        
        // 添加打印入库单按钮
        if (frm.doc.docstatus === 1) {
            frm.add_custom_button(__('打印入库单'), function() {
                print_receipt(frm);
            });
        }
    },
    
    warehouse: function(frm) {
        // 当仓库改变时，验证仓库状态
        if (frm.doc.warehouse) {
            frappe.call({
                method: 'frappe.client.get_value',
                args: {
                    doctype: 'Scrap Warehouse',
                    filters: {name: frm.doc.warehouse},
                    fieldname: 'status'
                },
                callback: function(r) {
                    if (r.message && r.message.status !== '启用') {
                        frappe.msgprint(__('所选仓库未启用，请选择其他仓库'));
                        frm.set_value('warehouse', '');
                    }
                }
            });
        }
    },
    
    scrap_materials: function(frm) {
        // 当余料列表改变时，计算总数量
        calculate_total_quantity(frm);
    },
    
    receipt_id: function(frm) {
        // 入库单编号格式化为大写
        if (frm.doc.receipt_id) {
            frm.set_value('receipt_id', frm.doc.receipt_id.toUpperCase());
        }
    }
});

// 子表事件
frappe.ui.form.on('Scrap Receipt Item', {
    scrap_materials_add: function(frm, cdt, cdn) {
        // 添加新行时，设置默认值
        let row = locals[cdt][cdn];
        if (!row.quantity) {
            frappe.model.set_value(cdt, cdn, 'quantity', 1);
        }
    },
    
    scrap_materials_remove: function(frm, cdt, cdn) {
        // 删除行时，重新计算总数量
        calculate_total_quantity(frm);
    },
    
    quantity: function(frm, cdt, cdn) {
        // 数量改变时，重新计算总数量
        calculate_total_quantity(frm);
    }
});

// 提交审批函数
function submit_for_approval(frm) {
    frappe.confirm(
        '确定要提交此入库单进行审批吗？',
        function() {
            frappe.call({
                method: 'scrap_management.scrap_management.doctype.scrap_receipt.scrap_receipt.submit_for_approval',
                args: {
                    docname: frm.docname
                },
                callback: function(r) {
                    if (!r.exc) {
                        frappe.show_alert({
                            message: __('入库单已提交审批'),
                            indicator: 'green'
                        });
                        frm.reload_doc();
                    }
                }
            });
        }
    );
}

// 审批函数
function approve_receipt(frm, approve) {
    let action_text = approve ? '通过' : '拒绝';
    frappe.confirm(
        `确定要${action_text}此入库单吗？`,
        function() {
            frappe.call({
                method: 'scrap_management.scrap_management.doctype.scrap_receipt.scrap_receipt.approve',
                args: {
                    docname: frm.docname,
                    approve: approve
                },
                callback: function(r) {
                    if (!r.exc) {
                        frappe.show_alert({
                            message: __('入库单已' + action_text),
                            indicator: 'green'
                        });
                        frm.reload_doc();
                    }
                }
            });
        }
    );
}

// 计算总数量函数
function calculate_total_quantity(frm) {
    let total = 0;
    if (frm.doc.scrap_materials) {
        for (let i = 0; i < frm.doc.scrap_materials.length; i++) {
            if (frm.doc.scrap_materials[i].quantity) {
                total += parseFloat(frm.doc.scrap_materials[i].quantity);
            }
        }
    }
    frm.set_value('total_quantity', total);
}

// 显示余料详情函数
function show_scrap_materials_details(frm) {
    let dialog = new frappe.ui.Dialog({
        title: '余料详情',
        fields: [
            {
                fieldname: 'scrap_materials_html',
                fieldtype: 'HTML'
            }
        ]
    });
    
    // 生成余料详情HTML
    let html = `
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>余料编号</th>
                <th>材料类型</th>
                <th>材料名称</th>
                <th>花色</th>
                <th>尺寸</th>
                <th>数量</th>
                <th>库位</th>
            </tr>
        </thead>
        <tbody>
    `;
    
    frm.doc.scrap_materials.forEach(function(item) {
        html += `
        <tr>
            <td>${item.scrap_material}</td>
            <td>${item.material_type}</td>
            <td>${item.material_name}</td>
            <td>${item.color_pattern}</td>
            <td>${item.length} x ${item.width} x ${item.thickness}</td>
            <td>${item.quantity} ${item.unit}</td>
            <td>${item.location}</td>
        </tr>
        `;
    });
    
    html += `
        </tbody>
    </table>
    `;
    
    dialog.fields_dict.scrap_materials_html.$wrapper.html(html);
    dialog.show();
}

// 打印入库单函数
function print_receipt(frm) {
    // 创建入库单内容
    let receipt_content = `
    <div style="font-family: Arial, sans-serif; padding: 20px;">
        <div style="text-align: center; margin-bottom: 20px;">
            <h2>余料入库单</h2>
        </div>
        <div style="margin-bottom: 20px;">
            <p><strong>入库单编号:</strong> ${frm.doc.receipt_id}</p>
            <p><strong>入库日期:</strong> ${frm.doc.receipt_date}</p>
            <p><strong>入库仓库:</strong> ${frm.doc.warehouse}</p>
            <p><strong>来源类型:</strong> ${frm.doc.source_type}</p>
            <p><strong>来源单据:</strong> ${frm.doc.source_document || ''}</p>
            <p><strong>总数量:</strong> ${frm.doc.total_quantity}</p>
            <p><strong>状态:</strong> ${frm.doc.status}</p>
        </div>
        <div style="margin-bottom: 20px;">
            <h3>余料列表</h3>
            <table style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="background-color: #f2f2f2;">
                        <th style="border: 1px solid #ddd; padding: 8px;">余料编号</th>
                        <th style="border: 1px solid #ddd; padding: 8px;">材料类型</th>
                        <th style="border: 1px solid #ddd; padding: 8px;">材料名称</th>
                        <th style="border: 1px solid #ddd; padding: 8px;">花色</th>
                        <th style="border: 1px solid #ddd; padding: 8px;">尺寸</th>
                        <th style="border: 1px solid #ddd; padding: 8px;">数量</th>
                        <th style="border: 1px solid #ddd; padding: 8px;">库位</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    frm.doc.scrap_materials.forEach(function(item) {
        receipt_content += `
        <tr>
            <td style="border: 1px solid #ddd; padding: 8px;">${item.scrap_material}</td>
            <td style="border: 1px solid #ddd; padding: 8px;">${item.material_type}</td>
            <td style="border: 1px solid #ddd; padding: 8px;">${item.material_name}</td>
            <td style="border: 1px solid #ddd; padding: 8px;">${item.color_pattern}</td>
            <td style="border: 1px solid #ddd; padding: 8px;">${item.length} x ${item.width} x ${item.thickness}</td>
            <td style="border: 1px solid #ddd; padding: 8px;">${item.quantity} ${item.unit}</td>
            <td style="border: 1px solid #ddd; padding: 8px;">${item.location}</td>
        </tr>
        `;
    });
    
    receipt_content += `
                </tbody>
            </table>
        </div>
        <div style="margin-top: 30px;">
            <p><strong>备注:</strong> ${frm.doc.notes || ''}</p>
        </div>
        <div style="margin-top: 30px;">
            <p><strong>提交人:</strong> ${frm.doc.submitted_by || ''}</p>
            <p><strong>提交时间:</strong> ${frm.doc.submitted_date || ''}</p>
            <p><strong>审核人:</strong> ${frm.doc.approved_by || ''}</p>
            <p><strong>审核时间:</strong> ${frm.doc.approved_date || ''}</p>
        </div>
    </div>
    `;
    
    // 打开打印窗口
    let print_window = window.open('', '_blank');
    print_window.document.write(`
    <html>
    <head>
        <title>余料入库单打印</title>
        <style>
            @media print {
                body { margin: 0; padding: 10px; }
                .no-print { display: none; }
            }
        </style>
    </head>
    <body>
        ${receipt_content}
        <div class="no-print" style="margin-top: 20px; text-align: center;">
            <button onclick="window.print()">打印</button>
            <button onclick="window.close()">关闭</button>
        </div>
        <script>
            window.onload = function() {
                // 自动打开打印对话框
                setTimeout(function() {
                    window.print();
                }, 500);
            }
        </script>
    </body>
    </html>
    `);
}